package com.cyj.dream.core.constant.users;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 在项目的任意位置获取当前Request
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.constant.users
 * @Author: ChenYongJia
 * @CreateTime: 2021-10-25 13:35
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class RequestContext {

    /**
     * @return
     * @throws IllegalStateException 当前线程不是web请求抛出此异常.
     * @Description: 获取当前request
     * @Title: getCurrentRequest
     * @author： ChenYongJia
     * @date： 2020-12-9 15:07:41
     */
    public static HttpServletRequest getCurrentRequest() throws IllegalStateException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new IllegalStateException("当前线程中不存在 Request 上下文信息");
        }
        return servletRequestAttributes.getRequest();
    }

    /**
     * 返回当前线程上下文response信息
     * @return HttpServletResponse
     * @date 2021/4/17 9:37
     * @author ChenYongJia
     * @version 1.0
     */
    public static HttpServletResponse getCurrentResponseInfo() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new IllegalStateException("当前线程中不存在 response 上下文信息");
        }
        return servletRequestAttributes.getResponse();
    }

}
